package com.mg.yygh.user.api;

import com.alibaba.fastjson.JSONObject;
import com.mg.yygh.common.helper.JwtHelper;
import com.mg.yygh.common.result.Result;
import com.mg.yygh.model.user.UserInfo;
import com.mg.yygh.user.service.UserInfoService;
import com.mg.yygh.user.utils.ConstantPropertiesUtil;
import com.mg.yygh.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author M_Dragon
 * @date 2022/9/8/008 17:15
 */
@Api(tags = "微信登录")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeixinApiController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("callback")
    public String callback(String code, String state) {
        //获取授权临时票据code值
        System.out.println("微信授权服务器回调。。。。。。");
        System.out.println("state = " + state);
        System.out.println("code = " + code);

        // 使用code和appid以及appscrect 绑定到请求地址
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");
        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);
        String accessTokenInfo = null;
        try {
            // 用code和appid以及appscrect绑定好的请求地址获取access_token和openid
            accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo" + accessTokenInfo);

            // 将access_token和openid 绑定到新的请求地址
            JSONObject resultJson = JSONObject.parseObject(accessTokenInfo);
            String accessToken = resultJson.getString("access_token");
            String openid = resultJson.getString("openid");
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                    "?access_token=%s" +
                    "&openid=%s";
            String userInfoUrl = String.format(baseUserInfoUrl, accessToken, openid);
            // 根据openid查用户表
            UserInfo userInfo = userInfoService.getWxInfo(openid);
            // 用户不存在，获取信息并存入表
            if (userInfo == null)
            {
                //  通过access_token和openid 绑定好的请求地址 获取resultUserInfo用户信息
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println(resultUserInfo);


                //解析用户信息
                JSONObject UserResult = JSONObject.parseObject(resultUserInfo);
                // 昵称
                String nickname = (String) UserResult.get("nickname");
                // 头像
                String headImgUrl = (String) UserResult.get("headimgurl");

                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }
            // map封装返回数据name，openId
            Map<String, Object> map = new HashMap<>();
            // 返回name回前端，如果空，用nickname，再者，用phone
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);

            // 返回openId,如果phone为空，openId有值,进行后续绑定
            //  如果phone不为空则表示，已经绑定
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", openid);
            } else {
                map.put("openid", "");
            }
            // 工具类生成token
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            // 重定向到前端页面
            return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL
                    + "/weixin/callback?token="+map.get("token")
                    +"&openid="+map.get("openid")+
                    "&name="+ URLEncoder.encode((String)map.get("name"),"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 获取微信登录参数
     */
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result genQrConnect(HttpSession session) throws UnsupportedEncodingException {
        String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "UTF-8");
        Map<String, Object> map = new HashMap<>();
        map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
        map.put("redirect_Uri", redirectUri);
        map.put("scope", "snsapi_login");
        map.put("state", System.currentTimeMillis() + "");//System.currentTimeMillis()+""
        return Result.ok(map);
    }
}